package com.stylefeng.guns.modular.wz.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.common.constant.Consts;
import com.stylefeng.guns.common.constant.factory.ConstantFactory;
import com.stylefeng.guns.common.constant.factory.PageFactory;
import com.stylefeng.guns.common.persistence.dao.PfFileMapper;
import com.stylefeng.guns.common.persistence.model.PfFile;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.core.shiro.ShiroKit;
import com.stylefeng.guns.modular.wz.service.IPfFileService;
import com.stylefeng.guns.modular.wz.util.AliOssUtil;
import com.stylefeng.guns.modular.wz.warpper.PfFileWarpper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 文件管理控制器
 *
 * @author fengshuonan
 * @Date 2018-04-20 16:56:13
 */
@Controller
@RequestMapping("/pfFile")
public class PfFileController extends BaseController {

    private String PREFIX = "/wz/pfFile/";
    private String SYS_PREFIX = "/wz/wzSys/startPage/";

    @Autowired
    private IPfFileService pfFileService;
    @Autowired
    private PfFileMapper pfFileMapper;

    /**
     * 跳转到文件管理首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "pfFile.html";
    }

    /**
     * 跳转到启动页图片
     */
    @RequestMapping("startPage")
    public String startPage() {
        return SYS_PREFIX + "startPage.html";
    }

    /**
     * 跳转到添加文件管理
     */
    @RequestMapping("/pfFile_add")
    public String pfFileAdd() {
        return PREFIX + "pfFile_add.html";
    }

    /**
     * 跳转到修改文件管理
     */
    @RequestMapping("/pfFile_update/{pfFileId}")
    public String pfFileUpdate(@PathVariable Integer pfFileId, Model model) {
        PfFile pfFile = pfFileService.selectById(pfFileId);
        model.addAttribute("item", pfFile);
        model.addAttribute("type", ConstantFactory.me().getDictsByName("文件类型", pfFile.getType()));
        model.addAttribute("subtype", ConstantFactory.me().getDictsByName("图片文件类型", pfFile.getSubtype()));
        model.addAttribute("status", ConstantFactory.me().getDictsByName("文件状态", pfFile.getStatus()));
        model.addAttribute("fileUrl", Consts.DOMAIN + pfFile.getFileUrl());
        LogObjectHolder.me().set(pfFile);
        return PREFIX + "pfFile_edit.html";
    }

    /**
     * 获取文件管理列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(String condition,String type) {
        Page<PfFile> page = new PageFactory<PfFile>().defaultPage();
        List<Map<String, Object>> list = pfFileMapper.selectMapsPage(page, new EntityWrapper<PfFile>().orderBy("status", true).orderBy("create_time", false));
        if(StringUtils.isNotBlank(condition)&&StringUtils.isNotBlank(type)){
            List<Map<String, Object>> list1 = pfFileMapper.selectMapsPage(page, new EntityWrapper<PfFile>().orderBy("status", true).orderBy("create_time", false).like("name",condition).eq("type",type));
            page.setRecords((List<PfFile>) new PfFileWarpper(list1).warp());
            return super.packForBT(page);
        }
        if(StringUtils.isNotBlank(condition)){
            List<Map<String, Object>> list1 = pfFileMapper.selectMapsPage(page, new EntityWrapper<PfFile>().orderBy("status", true).orderBy("create_time", false).like("name",condition));
            page.setRecords((List<PfFile>) new PfFileWarpper(list1).warp());
            return super.packForBT(page);
        }
        if(StringUtils.isNotBlank(type)){
            List<Map<String, Object>> list1 = pfFileMapper.selectMapsPage(page, new EntityWrapper<PfFile>().orderBy("status", true).orderBy("create_time", false).eq("type",type));
            page.setRecords((List<PfFile>) new PfFileWarpper(list1).warp());
            return super.packForBT(page);
        }
        page.setRecords((List<PfFile>) new PfFileWarpper(list).warp());
        return super.packForBT(page);
    }

    /**
     * 获取启动页图片文件管理列表
     */
    @RequestMapping(value = "/startPage.list")
    @ResponseBody
    public Object startPageList(String condition) {
        Page<PfFile> page = new PageFactory<PfFile>().defaultPage();
        List<Map<String, Object>> list = pfFileMapper.selectMapsPage(page, new EntityWrapper<PfFile>().orderBy("status", true).orderBy("create_time", false).eq("subtype", 5));
        page.setRecords((List<PfFile>) new PfFileWarpper(list).warp());
        return super.packForBT(page);
    }

    /**
     * 新增文件管理
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(PfFile pfFile, String avatar, String type, HttpServletRequest request) throws Exception {
        if ("1".equals(type)) {
            if (!StringUtils.isNotBlank(avatar)) {
                return super.SUCCESS_TIP.fail("请上传一张图片!");
            }
            //上传图片到aliOss
            boolean r = AliOssUtil.putObject(avatar);
            if (r) {
                String WidthAndHeight=AliOssUtil.getPicWidthAndHeight(avatar);
                pfFile.setBucketName(Consts.bucketName);
                pfFile.setCreateTime(new Date());
                pfFile.setFileUrl(avatar);
                pfFile.setSize(AliOssUtil.getFileSize(avatar).toString());
                pfFile.setModifierId(ShiroKit.getUser().getId());
                pfFile.setModifierName(ShiroKit.getUser().getName());
                pfFile.setWidth(Double.parseDouble(WidthAndHeight.split(",")[0]));
                pfFile.setLength(Double.parseDouble(WidthAndHeight.split(",")[1]));
                boolean b = pfFileService.insert(pfFile);
                if (b) {
                    return super.SUCCESS_TIP;
                }
            }
//        List list = AliOssUtil.getObjectListing(pfFile.getBucketName());
            return super.SUCCESS_TIP.fail("操作失败!");
        } else {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            MultipartFile file = multiRequest.getFile("radioFile");
            if (file != null && file.getSize() != 0) {
                String fileName = file.getOriginalFilename();
                String[] fileType= fileName.split("\\.");
                if(!fileType[1].equals("mp4")){
                    return super.SUCCESS_TIP.fail("仅支持上传MP4类型文件!");
                }
                String firstKey = UUID.randomUUID().toString() + ".mp4";
                boolean r = AliOssUtil.putRadio(file.getInputStream(), firstKey);
                if (r) {
                    pfFile.setBucketName(Consts.bucketName);
                    pfFile.setCreateTime(new Date());
                    pfFile.setFileUrl(firstKey);
                    pfFile.setSize(file.getSize() + "");
                    pfFile.setModifierId(ShiroKit.getUser().getId());
                    pfFile.setModifierName(ShiroKit.getUser().getName());
                    boolean b = pfFileService.insert(pfFile);
                    if (b) {
                        return super.SUCCESS_TIP;
                    }
                }
            } else {
                return super.SUCCESS_TIP.fail("请选择视频!");
            }
            return super.SUCCESS_TIP.fail("操作失败!");
        }
    }

    /**
     * 删除文件管理
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Long pfFileId) throws Exception {
        PfFile pfFile = pfFileService.selectById(pfFileId);
        if (pfFile.getStatus() == 2) {
            return SUCCESS_TIP.fail("使用中不可删除!");
        }
        AliOssUtil.deleteObject(pfFile.getFileUrl());
        pfFileService.deleteById(pfFileId);
        return SUCCESS_TIP;
    }

    /**
     * 修改文件管理
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(PfFile pfFile) {
        pfFileService.updateById(pfFile);
        return super.SUCCESS_TIP;
    }

    /**
     * 文件管理详情
     */
    @RequestMapping(value = "/detail/{pfFileId}")
    @ResponseBody
    public Object detail(@PathVariable("pfFileId") Integer pfFileId) {
        return pfFileService.selectById(pfFileId);
    }


    @RequestMapping(value = "/getUrl")
    @ResponseBody
    public Object getUrl(String fileId,Integer type) {
        if (!StringUtils.isNotBlank(fileId)) {
            return null;
        }
        PfFile pfFile = pfFileService.selectById(Long.parseLong(fileId));

        if (pfFile == null) {
            return SUCCESS_TIP.fail("文件id:" + fileId + " 无效!");
        }
        if(pfFile.getType()==1 && type==2){
            return SUCCESS_TIP.fail("填写错误 @_@#  图片id:" + fileId + " 为视频id，重新填写!");
        }
        if(pfFile.getType()==2 && type==1){
            return SUCCESS_TIP.fail("填写错误 @_@#  视频id:" + fileId + " 为图片id，重新填写!");
        }
        if(pfFile.getType()==1){
            return Consts.DOMAIN + pfFile.getFileUrl();
        }else if(pfFile.getType()==2){
            StringBuffer sb = new StringBuffer();
            sb.append(Consts.DOMAIN + pfFile.getFileUrl()+",");
            sb.append(pfFile.getWidth()+",");
            sb.append(pfFile.getLength()+",");
            sb.append(pfFile.getTime()+",");
            sb.append(pfFile.getSize());
            return sb;
        }else {
            return null;
        }
    }

    @RequestMapping(value = "/getIdByUrl")
    @ResponseBody
    public Object getIdByUrl(String fileUrl) {
        PfFile pfFile = pfFileService.selectOne(new EntityWrapper<PfFile>().eq("file_url", fileUrl));
        if (pfFile == null) {
            return SUCCESS_TIP.fail("找到不图片");
        }
        return pfFile.getFileId();
    }

}
